import 'dart:async';

import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/dialog/delete_account_check_dialog.dart';
import 'package:distribution_mall_flutter/entity/delete_account/delete_account_check_entity.dart';
import 'package:distribution_mall_flutter/entity/delete_account/delete_account_send_code_entity.dart';
import 'package:distribution_mall_flutter/ext/riverpod_ext.dart';
import 'package:distribution_mall_flutter/generated/json/base/json_field.dart';
import 'package:distribution_mall_flutter/generated/json/delete_account_verify.g.dart';
import 'package:distribution_mall_flutter/http/modules/delete_account.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:flutter/material.dart';
import 'package:phone_numbers_parser/phone_numbers_parser.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'delete_account_verify.g.dart';

@riverpod
class DeleteAccountVerify extends _$DeleteAccountVerify {
  @override
  Future<DeleteAccountCheckBody?> build() async {
    return (await DeleteAccountApi.check()).data;
  }

  Future<void> sendSmsCode(bool isPhone, String accountName) async {
    await DeleteAccountApi.onSendSmsOTP({
      'codeType': 'TWO_FACTOR',
      'endpoint': 'DISTRIBUTION_MALL',
      'receiver': accountName,
      'receiverType': isPhone ? 'PHONE' : 'EMAIL'
    });
  }

  ///提交验证码
  Future<void> getTemporaryToken(
    String accountType,
    String accountName,
    bool isPhone,
    String code,
  ) async {
    (await DeleteAccountApi.getTemporaryToken(
            accountName,
            isPhone ? 'PHONE' : 'EMAIL',
            'TWO_FACTOR',
            code,
            ref.read(deleteAccountSendCodeProvider).codeResponse!.checkCode))
        .yes((value) {
      appRouter.replace(DeleteAccountDeletingLoadingRoute(
          captchaToken: value!.captchaToken,
          accountType: accountType,
          accountName: accountName));
    });
  }
}

///枚举,默认状态,发送中,倒计时,倒计时结束
enum SendCodeState { Default, CountingDown, CountDownEnd }

@JsonSerializable()
class DeleteAccountSendCodeState {
  @JSONField(isEnum: true)
  SendCodeState type = SendCodeState.Default;
  int countDown = 0;
  DeleteAccountSendCodeBody? codeResponse;

  DeleteAccountSendCodeState();

  factory DeleteAccountSendCodeState.fromJson(Map<String, dynamic> json) =>
      $DeleteAccountSendCodeStateFromJson(json);

  Map<String, dynamic> toJson() => $DeleteAccountSendCodeStateToJson(this);
}

@riverpod
class DeleteAccountSendCode extends _$DeleteAccountSendCode {
  Timer? timer;

  @override
  DeleteAccountSendCodeState build() {
    WidgetsBinding.instance.addPostFrameCallback((_) {});
    return DeleteAccountSendCodeState();
  }

  Future<void> sendSmsCode(bool isPhone, String accountName) async {
    if (state.type == SendCodeState.CountingDown) {
      return;
    }
    String receiver;

    if (isPhone) {
      receiver = accountName;
      // receiver = PhoneNumber.parse(accountName).countryCode+PhoneNumber.parse(accountName).nsn;
    } else {
      receiver = accountName;
    }
    (await DeleteAccountApi.onSendSmsOTP({
      'codeType': 'TWO_FACTOR',
      'endpoint': 'DISTRIBUTION_MALL',
      'receiver': receiver,
      'receiverType': isPhone ? 'PHONE' : 'EMAIL'
    }))
        .yes((value) {
      state = state.copyWith(codeResponse: value!);
      startTime(value.sendCoolDownSecond!);
    });
  }

  void startTime(int time) {
    onDispose();
    state = state.copyWith(type: SendCodeState.CountingDown, countDown: time);
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.countDown - 1 <= 0) {
        onDispose();
        state = state.copyWith(type: SendCodeState.CountDownEnd, countDown: 0);
      }
      state = state.copyWith(countDown: state.countDown - 1);
    });
  }

  onDispose() {
    println('销毁');
    timer?.cancel();
    timer = null;
  }
}
